<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomTag\Action\Dashboard;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\RoomTag\Contract\RoomTagContract;
use MoChat\Plugin\RoomTag\Contract\RoomTagGroupContract;

/**
 * 创建客户群标签.
 *
 * Class Store
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var RoomTagGroupContract
     */
    protected $roomTagGroupService;

    /**
     * @Inject
     * @var RoomTagContract
     */
    protected $roomTagService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/roomTag/store", methods="POST")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) != 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 接收参数
        $params['groupName'] = $this->request->input('groupName', '');
        $params['id'] = (int) $this->request->input('id', 0);
        $params['tags'] = $this->request->input('tags', []);

        // 验证参数
        $this->validated($params);
        // 处理参数
        $this->handleParam($user, $params);
        // 数据操作
        Db::beginTransaction();
        try {
            // 创建群标签组
            $data = [
                'group_name' => $params['groupName'],
                'corp_id' => user()['corpIds'][0],
                'tenant_id' => user('tenantId'),
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $params['id'] = $this->roomTagGroupService->createRoomTagGroup($data);
            // 添加群标签
            if (! empty($params['tags'])) {
                $data = [];
                foreach ($params['tags'] as $k => $v) {
                    $data[$k]['name'] = $v['name'];
                    $data[$k]['room_tag_group_id'] = $params['id'];
                    $data[$k]['corp_id'] = user()['corpIds'][0];
                    $data[$k]['tenant_id'] = user('tenantId');
                    $data[$k]['created_at'] = date('Y-m-d H:i:s');
                }

                $this->roomTagService->createRoomTags($data);
            }

            Db::commit();
            return [$params['id']];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '添加群标签失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'groupName' => 'required|string',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'groupName.required' => '标签组名称 必传',
        ];
    }

    /**
     * 处理参数.
     * @param array $user 用户信息
     * @param array $params 接受参数
     * @throws \JsonException
     */
    private function handleParam(array $user, array $params): void
    {
        // 校验标签组名称重复
        if (! empty($params['groupName']) && ! empty($this->roomTagGroupService->getRoomTagGroupByCorpIdName($user['corpIds'][0], $params['groupName']))) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '标签组名称重复，不可操作');
        }
        if ($params['id'] > 0) {
            foreach ($params['tags'] as $item) {
                if (! empty($this->roomTagService->getRoomTagByGroupIdName($params['id'], $item))) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '不可创建同名标签:' . $item);
                }
            }
        }
    }
}
